package combat;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

import org.bukkit.Bukkit;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

public class Resistance implements ActionListener {
	private static final PotionEffectType RESISTANCE = PotionEffectType.DAMAGE_RESISTANCE;
	private final LivingEntity target;
	private final Timer timer, godApple;
	private int stacks, godAppleDuration, godAppleTicks;

	public Resistance(LivingEntity target) {
		this.target = target;
		stacks = 0;
		godAppleDuration = 0;
		godAppleTicks = 0;
		godApple = new Timer(1000, this);
		godApple.setInitialDelay(0);
		godApple.setActionCommand("apple");
		timer = new Timer(10000, this);
		timer.setRepeats(false);
		timer.setActionCommand("stop");
		Bukkit.
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		if (event.getActionCommand().equals("apple")) {
			godAppleTicks++;
		}
		if (event.getActionCommand().equals("stop")) {
			timer.stop();
			godApple.stop();
			if (godAppleDuration > 0) {
				for (PotionEffect effect : target.getActivePotionEffects()) {
					if (effect.getType().equals(PotionEffectType.FIRE_RESISTANCE)) {
						if (effect.getAmplifier() == 0) {
							if (Math.abs((effect.getDuration() + godAppleTicks * 20)
									- godAppleDuration) <= 4) {
								PotionEffect potion = new PotionEffect(RESISTANCE,
										effect.getDuration(), 0);
								target.addPotionEffect(potion);																
							}
							else {
								PotionEffect potion = new PotionEffect(RESISTANCE,
										godAppleDuration - 20 * godAppleTicks, 0);
								target.addPotionEffect(potion);
							}
						}
					}
				}				
			}
			ResistanceManager.remove(target);
		}
	}

	public void debuff() {
		timer.stop();
		for (PotionEffect effect : target.getActivePotionEffects()) {
			if (effect.getType().equals(RESISTANCE)) {
				if (effect.getAmplifier() == 0) {
					godApple.stop();
					if (godAppleDuration < effect.getDuration()) {
						stacks = 0;
					}
					godAppleDuration = effect.getDuration();
					godApple.restart();
				}
			}
		}
		stacks--;
		if (stacks < 0) {
			PotionEffect potion = new PotionEffect(RESISTANCE, 200, stacks);
			target.addPotionEffect(potion, true);
		}
		if (target instanceof Player) {
			Player player = (Player) target;
			player.sendMessage("STACKS: " + stacks);
		}
		timer.restart();
	}
	
	public void buff() {
		stacks++;
		if (stacks >= 0) {
			target.addPotionEffect(new PotionEffect(RESISTANCE, 200, 0));
		}
	}
}
